﻿using Gameplay.PVE;
using LogSystem;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

namespace Yoozoo.Gameplay.City
{
    /// <summary>
    /// 用于内城房间同步光照信息 xxx_before使用xxx的信息
    /// </summary>
    [ExecuteAlways]
    public class CityLightMapSync : MonoBehaviour
    {
        public List<MeshRendererData> meshRendererDataList;

        public Transform originRoot;

        /// <summary>
        /// 目标预制体的路径，用于originRoot丢失后重新绑定
        /// </summary>
        public string OriginPrefabAssetPath;

        /// <summary>
        /// 是否同步ReflectionProbe
        /// </summary>
        public bool IsSyncReflectionProbe;

        private void GetLightMap()
        {
            if (originRoot != null)
            {
                var meshRenderers = originRoot.GetComponentsInChildren<MeshRenderer>();
                meshRendererDataList = new List<MeshRendererData>();

                for (int i = 0; i < meshRenderers.Length; i++)
                {
                    var ms = meshRenderers[i];
                    MeshRendererData rendererData = new MeshRendererData();
                    rendererData.lightmapIndex = ms.lightmapIndex;
                    rendererData.renderIndex = i;
                    rendererData.lightmapScaleOffset = ms.lightmapScaleOffset;
                    meshRendererDataList.Add(rendererData);
                }
            }
        }

        private void OnEnable()
        {
            Sync();
        }

        public bool Sync()
        {
            if (!originRoot && !FindOriginPrefab())
            {
                Debug.LogError(LogModule.City, $"{name}光照信息同步目标丢失", gameObject);
                return false;
            }

#if UNITY_EDITOR
            if (!UnityEditor.PrefabUtility.IsOutermostPrefabInstanceRoot(originRoot.gameObject) && !Application.isPlaying)
            {
                Debug.LogError(LogModule.City, $"{name}光照信息同步目标不是预制体", gameObject);
                return false;
            }

            OriginPrefabAssetPath = UnityEditor.PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(originRoot);
#endif

            bool isSuccess = true;
            GetLightMap();
            if (!SetLightMap())
            {
                isSuccess = false;
                Debug.LogError(LogModule.City, $"{name}光照信息同步失败", gameObject);
            }

            if (IsSyncReflectionProbe)
            {
                isSuccess = SyncReflectionProbe();
            }

            return isSuccess;
        }

        private bool SyncReflectionProbe()
        {
            bool isSuccess = true;
            var sourceReflectionProbe = originRoot.GetComponentInChildren<ReflectionProbe>();
            if (sourceReflectionProbe)
            {
                if (sourceReflectionProbe.mode != ReflectionProbeMode.Baked)
                {
                    isSuccess = false;
                    Debug.LogError(LogModule.City, $"{name} 目标反射探针不是Baked模式", gameObject);
                }
                else
                {
                    if (sourceReflectionProbe.bakedTexture == null)
                    {
                        isSuccess = false;
                        Debug.LogError(LogModule.City, $"{name} 目标反射探针没有烘焙", gameObject);
                    }
                }
            }
            else
            {
                isSuccess = false;
                Debug.LogError(LogModule.City, $"{name} 目标没有使用反射探针", gameObject);
            }

            var targetReflectionProbe = GetComponentInChildren<ReflectionProbe>();
            if (!targetReflectionProbe)
            {
                isSuccess = false;
                Debug.LogError(LogModule.City, $"{name} 自身没有使用反射探针", gameObject);
            }

            if (sourceReflectionProbe && targetReflectionProbe)
            {
                targetReflectionProbe.mode = ReflectionProbeMode.Baked;
                targetReflectionProbe.bakedTexture = sourceReflectionProbe.bakedTexture;
            }

            return isSuccess;
        }

        private bool FindOriginPrefab()
        {
            if (string.IsNullOrEmpty(OriginPrefabAssetPath))
                return false;

#if UNITY_EDITOR
            var asset = UnityEditor.AssetDatabase.LoadAssetAtPath<GameObject>(OriginPrefabAssetPath);
            if (!asset)
            {
                OriginPrefabAssetPath = "";
                return false;
            }

            var allObjects = FindObjectsOfType<Transform>();
            foreach (var o in allObjects)
            {
                if (UnityEditor.PrefabUtility.IsOutermostPrefabInstanceRoot(o.gameObject))
                {
                    string prefabAssetPath = UnityEditor.PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(o);
                    if (prefabAssetPath == OriginPrefabAssetPath)
                    {
                        originRoot = o;
                        return true;
                    }
                }
            }

            return false;
#else
            return true;
#endif
        }

        private bool SetLightMap()
        {
            var meshRenderers = GetComponentsInChildren<MeshRenderer>();
            if (meshRendererDataList != null && meshRendererDataList.Count == meshRenderers.Length)
            {
                for (int i = 0; i < meshRenderers.Length; i++)
                {
                    var ms = meshRenderers[i];
                    ms.lightmapIndex = meshRendererDataList[i].lightmapIndex;
                    ms.lightmapScaleOffset = meshRendererDataList[i].lightmapScaleOffset;
                }

                return true;
            }

            return false;
        }
    }
}
